import { connection } from './connection'

/**
 * 获取用户信息
 * @param {string} code
 * @param {function} callback
 */
const getUserInfo = (code:string,callback: () => void) => {
    connection.query('select * from user_info where code = ?', [code], callback)
};

/**
 * 新增今日事项
 * @param {Object} obj
 * @param {function} callback
 */
const addTodoList = (obj:object, callback: () => void) => {
    connection.query('insert into todo_list set ?', [obj], callback);
};

/**
 * 更新今日事项
 * @param {object} obj
 * @param {function} callback
 */
const updataTodoList = (obj: { content: string, finish: string, code: string }, callback: () => void) => {
    const { content, finish, code } = obj
    connection.query('update todo_list set content = ?, finish = ? where code = ?', [content, finish, code], callback)
};

/**
 * 删除今日事项
 * @param {Array} codes
 * @param {function} callback
 */
const delTodeList = (codes:string[], callback:() => void) => {
    let str = ''
    let list = codes.map(item => {
        return `"${item}"`
    })
    str = list.join(',')
    connection.query(`delete from todo_list where code in (${str})`, callback)
}
/**
 * 注册
 * @param {object} obj
 * @param {function} callback
 */
const register = (obj: {
    userName: string,
    passWord: string,
    nickName: string,
    acatar: string,
    admin: number,
    createTime: number,
    updataTime: number
}) => {
    return new Promise((resolve,reject) => {
        const { userName, passWord, acatar, nickName, admin, createTime, updataTime } = obj;
        connection.query('insert into user_info (userName,passWord,acatar,nickName,admin,createTime,updataTime) values (?,?,?,?,?,?,?)',
            [userName, passWord, acatar, nickName, admin, createTime, updataTime],
            (err, results) => {
                if (!err) {
                    resolve(results)
                } else {
                    reject(results)
                }
            }
        );
    })
}

/**
 * 查询是否存在用户数据
 * @param {string} userName
 * @returns {boolean}
 */
const paramsquery = (userName:string) => {
    return new Promise((resolve, rejects) => {
        connection.query('select * from user_info where userName = ?', [userName], (err, results) => {
            if (err) {
                rejects({ status: 400, desc: '查询失败' })
            }
            resolve({ status: 200, desc: '查询成功', data: results })
        })
    })
}


export {
    getUserInfo,
    updataTodoList,
    addTodoList,
    delTodeList,
    paramsquery,
    register
}